package com.example.testapp.activity.http;

import android.net.Uri;
import android.os.Message;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import java.io.IOException;
import java.net.SocketException;

/**
 * Created by l on 2016/8/1.
 */
public class MHttpEntity {

    private Message message;
    private HttpEntity httpEntity;
    public static final int succeed = 1;
    public static final int fail = 2;
    public static final int nonet = 3;

    public Message getMessage() {
        return message;
    }

    public void setMessage(Message message) {
        this.message = message;
    }

    public HttpEntity getHentity() {
        return httpEntity;
    }

    public void setHttpEntity(HttpEntity httpEntity) {
        this.httpEntity = httpEntity;
    }

    public static MHttpEntity sendHttpRequest(String str) {
        Log.i("TAG", System.currentTimeMillis()+"System.currentTimeMillis()333");
        MHttpEntity entity = new MHttpEntity();
        Message message = Message.obtain();
        HttpEntity he = null;
        HttpClient client = new DefaultHttpClient(); // 实例化得到一个网络连接对象
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 5000); //连接超时设置
        String  mstr = Uri.decode(str);// 将String类型转为uri.有中文则必有此句。
        HttpGet get = new HttpGet(mstr); // 创建Http请求(get请求)
        try {
            HttpResponse response = client.execute(get); // 执行一个请求
            if(response.getStatusLine().getStatusCode() == 200){
                he = response.getEntity(); // 获得数据实体
                message.arg1 = succeed; // 保存网络状态
            }else {
                message.arg1 = fail;// 保存网络状态
            }
        } catch (SocketException e) {
            message.arg1 = fail;
            e.printStackTrace();
        }catch (ClientProtocolException e){
            message.arg1 = fail;
            e.printStackTrace();
        }catch (IOException e){
            message.arg1 = fail;
            e.printStackTrace();
        }
        entity.setMessage(message);
        entity.setHttpEntity(he);
        Log.i("TAG", entity.getHentity() + " mhe.getHentity()");
        return entity;
    }
}
